import axios from 'axios';
import utils from '../utils/utils';
import db from '../store/localstorage';
import aesUtil from '../utils/aesUtils';
import _store from '@/store/store';
import { useStore } from 'vuex';
import nProgress from 'nprogress';
import 'nprogress/nprogress.css';
nProgress.configure({ showSpinner: false });
const store = useStore() || _store;

//是否开启websocket
export const websocket_status = false;
//环境配置
export const env = import.meta.env;
export const mode: string = env.MODE;
export const apiUrl: string = env.VITE_BASE_URL;
export const socketUrl: string = env.VITE_SOCKET_SERVER;
/**
 * 上传头
 */
export const getHeader = () => {
	let header = { Authorization: '', sign: '' };
	if (store?.state.account.token) {
		header.Authorization = store.state.account.token;
	}
	header.sign = aesUtil.encrypt(Date.now());
	return header;
};
/**
 * 上传地址
 * @returns {string}
 */
export const getUploadUrl = () => {
	return apiUrl + '/platform/info/upload';
};

/**
 * 编辑器文件上传
 * @param file
 * @param Editor
 * @param cursorLocation
 * @param resetUploader
 */
export const editorUpload = (file: any, Editor: any, cursorLocation: any, resetUploader: any) => {
	let formData = new FormData();
	formData.append('file', file);
	utils.loading();
	return ADMIN_REQUEST.post(getUploadUrl(), formData, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
		.then(ret => {
			utils.closeAll();
			utils.closeSpin();
			//把获取到的图片url 插入到鼠标所在位置 回显图片
			Editor.insertEmbed(cursorLocation, 'image', aesUtil.decrypt(ret.data, null));
			resetUploader();
		})
		.catch(err => {
			utils.closeAll();
			utils.closeSpin();
		});
};
export const doUp = (file: string | Blob) => {
	let formData = new FormData();
	formData.append('file', file);
	utils.loading();
	return ADMIN_REQUEST.post(getUploadUrl(), formData, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	});
};
// 统一配置
let ADMIN_REQUEST = axios.create({
	baseURL: apiUrl,
	responseType: 'json',
	validateStatus(status) {
		// 200 外的状态码都认定为失败
		return status === 200;
	}
});

// 拦截请求
ADMIN_REQUEST.interceptors.request.use(
	config => {
		nProgress.start();
		if (!config.headers) {
			config.headers = {};
		}
		// 有 token就带上
		if (db.get('USER_TOKEN') && typeof db.get('USER_TOKEN') == 'string') {
			config.headers.Authorization = db.get('USER_TOKEN');
		}
		config.headers.sign = aesUtil.encrypt(Date.now());
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

// 拦截响应
ADMIN_REQUEST.interceptors.response.use(
	response => {
		nProgress.done();
		utils.closeAll();
		utils.closeSpin();
		//下载文件返回数据判断
		if (response.data && response.data.type) {
			if (response.data.type == 'application/octet-stream') {
				return response.data;
			}
			if (response.data.type == 'application/json') {
				let reader = new FileReader();
				reader.readAsText(response.data, 'utf-8');
				reader.onload = () => {
					let error = JSON.parse(reader.result as string);
					utils.error(error.message + ' code：-' + error.code, 2000);
				};
				throw new Error(response.data);
			}
		}
		//登录身份过期
		if (response.data && response.data.code == 10000) {
			db.clear();
			utils.error('登录身份过期，请重新登录！', 2000).then(ret => {
				window.location.href = '/login';
			});
			return;
		}
		if (response.data && response.data.code && response.data.code != 200) {
			utils.error(response.data.message + ' code：-' + response.data.code, 2000);
			throw new Error(response.data.message + ',code:' + response.data.code);
		} else {
			return response.data;
		}
	},
	error => {
		nProgress.done();
		utils.closeAll();
		utils.closeSpin();
		utils.error(error.message);
		return Promise.reject(error);
	}
);

const request = {
	apiUrl,
	socketUrl,
	post(url: any, params: any) {
		return ADMIN_REQUEST.post(url, params);
	},
	put(url: any, params?: any) {
		return ADMIN_REQUEST.put(url, params, {
			transformRequest: [
				params => {
					let result = '';
					Object.keys(params).forEach(key => {
						if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
							result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&';
						}
					});
					return result;
				}
			],
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			}
		});
	},
	get(url: any, params?: any) {
		let _params;
		if (Object.is(params, undefined)) {
			_params = '';
		} else {
			_params = '?';
			for (let key in params) {
				if (params.hasOwnProperty(key) && params[key] !== null) {
					_params += `${key}=${params[key]}&`;
				}
			}
		}
		return ADMIN_REQUEST.get(`${url}${_params}`);
	},
	delete(url: any, params?: any) {
		let _params;
		if (Object.is(params, undefined)) {
			_params = '';
		} else {
			_params = '?';
			for (let key in params) {
				if (params.hasOwnProperty(key) && params[key] !== null) {
					_params += `${key}=${params[key]}&`;
				}
			}
		}
		return ADMIN_REQUEST.delete(`${url}${_params}`);
	},
	export(url: any, params = {}) {
		utils.loading();
		return ADMIN_REQUEST.post(url, params, {
			transformRequest: [
				params => {
					let result = '';
					Object.keys(params).forEach(key => {
						if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
							result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&';
						}
					});
					return result;
				}
			],
			responseType: 'blob'
		}).then(r => {
			const blob = r.data;
			// const blob = new Blob([r]);
			const fileName = `${new Date().getTime()}_导出结果.xlsx`;
			if ('download' in document.createElement('a')) {
				const elink = document.createElement('a');
				elink.download = fileName;
				elink.style.display = 'none';
				elink.href = URL.createObjectURL(blob);
				document.body.appendChild(elink);
				elink.click();
				URL.revokeObjectURL(elink.href);
				document.body.removeChild(elink);
			} else {
				const nav = window.navigator as any;
				nav.msSaveBlob(blob, fileName);
				// navigator.msSaveBlob(blob, fileName);
			}
		});
	},
	download(url: any, params?: any, filename?: any) {
		utils.loading();
		return ADMIN_REQUEST.post(url, params, {
			transformRequest: [
				params => {
					let result = '';
					Object.keys(params).forEach(key => {
						if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
							result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&';
						}
					});
					return result;
				}
			],
			responseType: 'blob'
		})
			.then(r => {
				const blob = r.data;
				// const blob = new Blob([r]);
				if ('download' in document.createElement('a')) {
					const elink = document.createElement('a');
					elink.download = filename;
					elink.style.display = 'none';
					elink.href = URL.createObjectURL(blob);
					document.body.appendChild(elink);
					elink.click();
					URL.revokeObjectURL(elink.href);
					document.body.removeChild(elink);
				} else {
					const nav = window.navigator as any;
					nav.msSaveBlob(blob, filename);
					// navigator.msSaveBlob(blob, filename);
				}
			})
			.catch(r => {
				console.error(r);
				utils.error('下载失败');
			});
	},
	upload(params: any) {
		return ADMIN_REQUEST.post(getUploadUrl(), params, {
			headers: {
				'Content-Type': 'multipart/form-data'
			}
		});
	}
};

export default request;
